package com.jiaying.patient.view;

import com.jiaying.patient.dao.PatientDao;
import com.jiaying.patient.domain.Department;
import com.jiaying.patient.domain.Patient;
import com.jiaying.patient.domain.Record;

import javax.swing.*;
import javax.swing.event.TableModelListener;
import javax.swing.table.TableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.List;

/**
 * 这是一个放在DesktopPane 上的窗体，
 * 需要继承一个特殊的类
 */
public class DoctorQueryPatientView extends JInternalFrame {

    //1.定义组件
    // 定义各个组件
    private JPanel panel_parent = null;// 主面板
    private JScrollPane panel_table=null;//可滚动面板
    private JPanel panel_buttons = null;// 按钮组面板

    private JTable table = null;// 表格控件，用来存放列表数据
    private JLabel lb_type = null;// 类型标签
    private JComboBox<String> cb_type = null;// 查询类型选择框，下拉框
    private JButton btn_search = null;// 查询按钮
    private JButton btn_edit = null;// 修改按钮
    private JButton btn_enterHospital=null;//入院按钮
    private JButton btn_delete = null;// 删除按钮
    private JButton btn_exit = null;// 退出按钮

    private PatientDao patientDao=new PatientDao();  //需要控制dao的创建，尽量采用单例模式

    int patientId=0;// 这是一个作用域需要放大的变量

    Patient patient=new Patient();// 这是一个作用域需要放大的变量

    //2.组件初始化
    private void init(){
        table = new JTable();  //表格控件需要先初始化，然后改到滚动面板
        table.addMouseListener(new MouseListener() {
            @Override
            public void mouseClicked(MouseEvent e) {
                System.out.println("您点击表格了。。。。。。。。。。。。。。。。。。。。");
                int rowIndex=table.getSelectedRow(); //索引从0开始
                //获取到患者的就诊卡号
                patientId=(Integer)table.getValueAt(rowIndex,0);
                //name   address  gender  cardnumber  keshiId
                String name=(String)table.getValueAt(rowIndex,1);
                String address=(String)table.getValueAt(rowIndex,5);
                int gender=table.getValueAt(rowIndex,2).equals("男")?1:0;
                String cardnumber=(String)table.getValueAt(rowIndex,3);
                int departmentId=table.getValueAt(rowIndex,7).equals("内科")?1:2;

                patient.setPatientId(patientId);
                patient.setGender(gender);
                patient.setHomeAddress(address);
                patient.setDepartment(new Department(departmentId));
                patient.setRealName(name);
                patient.setCardNumber(cardnumber);

            }

            @Override
            public void mousePressed(MouseEvent e) {

            }

            @Override
            public void mouseReleased(MouseEvent e) {

            }

            @Override
            public void mouseEntered(MouseEvent e) {

            }

            @Override
            public void mouseExited(MouseEvent e) {

            }
        });

        panel_parent=new JPanel(new BorderLayout());
        panel_table = new JScrollPane(table);
        panel_table.setBorder(BorderFactory.createTitledBorder(BorderFactory.createRaisedBevelBorder(), "患者信息列表"));


        panel_buttons = new JPanel(new GridLayout(8, 1, 0, 30));
        panel_buttons.setBorder(BorderFactory.createTitledBorder(BorderFactory.createRaisedBevelBorder(), "查询条件"));

        lb_type = new JLabel("查询类型：");
        cb_type = new JComboBox<String>(new String[] { "查询所有患者", "根据就诊卡号查询", "查询姓名查询" });
        btn_search = new JButton("查询");
        btn_search.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("你点击查询按钮了。。。。。。。。。。。。。。。。");
                //1.获取查询类型   2.根据查询类型进行查询得到结果  3.把结果展示到table控件中
                //1.获取查询类型
                int selectedIndex= cb_type.getSelectedIndex();  //从0开始
                switch(selectedIndex){
                    case 0:
                       // 2.根据查询类型进行查询得到结果  调用PatientDao查询所有患者
                        List<Patient> patientList=patientDao.selectAll();
                       // 3.把结果展示到table控件中
                        PatientDataModel patientDataModel=new PatientDataModel(patientList);
                        table.setModel(patientDataModel);
                        break;
                    case 1:
                        //根据就诊卡号查询
                        String patientId=JOptionPane.showInputDialog("请输入就诊卡号：");
                        System.out.println("patientId:"+patientId);
                        //调用dao根据就诊卡号查询患者信息，就可以了
                        Patient queryResult=patientDao.selectByPatientId(Integer.parseInt(patientId));
                        //一个对象---》塞入List
                        List<Patient> patients=new ArrayList<>();
                        patients.add(queryResult);
                        PatientDataModel patientDataModel1=new PatientDataModel(patients);
                        table.setModel(patientDataModel1);
                        break;
                    case 2:
                        // 根据姓名查询
                        break;
                    default:
                        break;
                }

            }
        });

        btn_enterHospital=new JButton("入院");
        btn_enterHospital.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                //思路：当医生点击按钮时：弹出模态框，供医生输入患者信息--》点击确定按钮保存数据到数据库
                showAddPatientDialog(null);//封装方法
            }
        });
        btn_edit = new JButton("修改");
        btn_edit.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("你点击修改按钮了。。。。。。。。。。。。");
                showEditPatientDialog(null,patient);

            }
        });




        btn_delete = new JButton("删除");
        btn_delete.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                //调用dao的删除方法，根据就诊卡号删除患者信息
                int result=JOptionPane.showConfirmDialog(null,"确认删除就诊卡号为"+patientId+"的患者信息吗？");
                System.out.println("result:"+result);
                if(result==0){
                    patientDao.deletePatientById(patientId);
                    JOptionPane.showMessageDialog(null,"删除成功");
                }
            }
        });
        btn_exit = new JButton("退出窗口");
        // 拼装

        //panel_table.add(table);  ？？？？？
        panel_table.setSize(600,400);

        panel_buttons.add(lb_type);
        panel_buttons.add(cb_type);
        panel_buttons.add(btn_search);
        panel_buttons.add(new JLabel());
        panel_buttons.add(btn_enterHospital);
        panel_buttons.add(btn_edit);
        panel_buttons.add(btn_delete);
        panel_buttons.add(btn_exit);

        panel_parent.add(panel_table,BorderLayout.CENTER);
        panel_parent.add(panel_buttons,BorderLayout.EAST);

        this.getContentPane().add(panel_parent);
    }

    //3.定义构造方法
    public DoctorQueryPatientView(){
        init();
        // 设置本窗体相关属性
        this.setTitle("患者信息查询界面");// 设置窗体的主题
        this.setIconifiable(true);// 设置窗体是否可以最小化
        this.setClosable(true);// 设置窗体是否可以关闭
        this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);// 设置窗体可以关闭，类型是隐藏自己，释放所占用内存
        this.setSize(800, 550);// 设置窗体大小
        this.setVisible(true);
    }

    //4.测试
    //这里写main方法测试不了

    //定义一个内部类
    private class PatientDataModel implements TableModel{

        private List<Patient> patientList;

        public PatientDataModel(List<Patient> patients){
            this.patientList=patients;
        }

        @Override
        public int getRowCount() {
            return patientList.size();
        }

        @Override
        public int getColumnCount() {
            return 8;
        }

        @Override
        public String getColumnName(int columnIndex) {
            String colName="";
            if(columnIndex==0){
                colName="就诊卡号";
            }else if(columnIndex==1){
                colName="真实姓名";
            }else if(columnIndex==2){
                colName="性别";
            }else if(columnIndex==3){
                colName="身份证号";
            }else if(columnIndex==4){
                colName="年龄";
            }else if(columnIndex==5){
                colName="住址";
            }else if(columnIndex==6){
                colName="状态";
            }else{
                colName="科室";
            }
            return colName;
        }

        @Override
        public Class<?> getColumnClass(int columnIndex) {
            return String.class;
        }

        @Override
        public boolean isCellEditable(int rowIndex, int columnIndex) {
            return false;
        }

        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
            Patient patient=patientList.get(rowIndex);
            if(columnIndex==0){
                return patient.getPatientId();
            }else if(columnIndex==1){
                return patient.getRealName();
            }else if(columnIndex==2){
                return patient.getGender()==1?"男":"女";
            }else if(columnIndex==3){
                return patient.getCardNumber();
            }else if(columnIndex==4){
                return patient.getAge();
            }else if(columnIndex==5){
                return patient.getHomeAddress();
            }else if(columnIndex==6){
                return patient.getState()==1?"入院":"出院";
            }else{
                return patient.getDepartment().getDepartmentName();
            }

        }

        @Override
        public void setValueAt(Object aValue, int rowIndex, int columnIndex) {

        }

        @Override
        public void addTableModelListener(TableModelListener l) {

        }

        @Override
        public void removeTableModelListener(TableModelListener l) {

        }
    }

    /**
     * 弹出入院操作的模态框
     * @param frame
     */
    private void showAddPatientDialog(JFrame frame){
        // 创建对话框
        JDialog dialog = new JDialog(frame, "请输入患者信息：", true);
        dialog.setLayout(new GridLayout(0, 2, 10, 10));
        dialog.setSize(700, 500);

        // 添加多个编辑字段
        dialog.add(new JLabel("真实姓名:"));
        JTextField nameField = new JTextField();
        dialog.add(nameField);

        dialog.add(new JLabel("性别:"));
        JTextField sexField = new JTextField();
        dialog.add(sexField);

        dialog.add(new JLabel("身份证号码:"));
        JTextField cardField = new JTextField();
        dialog.add(cardField);

        dialog.add(new JLabel("住址:"));
        JTextField addressField = new JTextField();
        dialog.add(addressField);

        dialog.add(new JLabel("科室:"));
        JComboBox<String> keshi=new JComboBox<>(new String[] { "内科", "外科"});//数据库目前只有两个科室
        dialog.add(keshi);

        dialog.add(new JLabel("主诉信息:"));
        JTextField record_readme = new JTextField();
        dialog.add(record_readme);

        // 添加按钮
        JButton saveButton = new JButton("保存");
        saveButton.addActionListener(e -> {
            // 获取所有字段值
            String name = nameField.getText();
            String sex = sexField.getText();
            String card = cardField.getText();
            String address = addressField.getText();
            Integer keshiNo = keshi.getSelectedIndex()+1;  //需要加1和数据库对应
            String readme = record_readme.getText();

            // 处理数据...
            //调用dao保存数据到数据库
            // 一堆数据----》患者对象----》传给dao保存
            Patient patient=new Patient();
            patient.setCardNumber(card);
            patient.setRecord(new Record(readme));
            patient.setState(1);
            patient.setRealName(name);
            patient.setDepartment(new Department(keshiNo));
            patient.setHomeAddress(address);
            patient.setGender(sex.equals("男")?1:0);

            boolean result=patientDao.insertPatient(patient);

            if(result){
                  JOptionPane.showMessageDialog(dialog,
                     "入院成功");
            }else{
                JOptionPane.showMessageDialog(dialog,"入院失败");
            }
            dialog.dispose();
        });

        JButton cancelButton = new JButton("取消");
        cancelButton.addActionListener(e -> dialog.dispose());

        dialog.add(saveButton);
        dialog.add(cancelButton);

        dialog.pack();
        dialog.setLocationRelativeTo(null);
        dialog.setVisible(true);
    }

    /**
     * 弹出修改患者信息的模态框
     */
    public void  showEditPatientDialog(JFrame frame,Patient patient){
        // 创建对话框
        JDialog dialog = new JDialog(frame, "请修改患者信息：", true);
        dialog.setLayout(new GridLayout(0, 2, 10, 10));
        dialog.setSize(700, 500);

        // 添加多个编辑字段
        dialog.add(new JLabel("真实姓名:"));
        JTextField nameField = new JTextField();
        nameField.setText(patient.getRealName());
        dialog.add(nameField);

        dialog.add(new JLabel("性别:"));
        JTextField sexField = new JTextField();
        sexField.setText(patient.getGender()==1?"男":"女");
        dialog.add(sexField);

        dialog.add(new JLabel("身份证号码:"));
        JTextField cardField = new JTextField();
        cardField.setText(patient.getCardNumber());
        dialog.add(cardField);

        dialog.add(new JLabel("住址:"));
        JTextField addressField = new JTextField();
        addressField.setText(patient.getHomeAddress());
        dialog.add(addressField);

        dialog.add(new JLabel("科室:"));
        JComboBox<String> keshi=new JComboBox<>(new String[] { "内科", "外科"});//数据库目前只有两个科室
        keshi.setSelectedIndex(patient.getDepartment().getDepartmentId()-1);
        dialog.add(keshi);


        // 修改按钮
        JButton editButton = new JButton("修改");
        editButton.addActionListener(e -> {
            // 获取所有字段值
            String name = nameField.getText();
            String sex = sexField.getText();
            String card = cardField.getText();
            String address = addressField.getText();
            Integer keshiNo = keshi.getSelectedIndex()+1;  //需要加1和数据库对应

            // 处理数据...
            //调用dao保存数据到数据库
            // 一堆数据----》患者对象----》传给dao保存
            Patient p=new Patient();
            p.setCardNumber(card);
            p.setState(1);
            p.setRealName(name);
            p.setDepartment(new Department(keshiNo));
            p.setHomeAddress(address);
            p.setGender(sex.equals("男")?1:0);
            p.setPatientId(patient.getPatientId());

            patientDao.editPatient(p);


            JOptionPane.showMessageDialog(dialog,"修改成功");

            dialog.dispose();
        });

        JButton cancelButton = new JButton("取消");
        cancelButton.addActionListener(e -> dialog.dispose());

        dialog.add(editButton);
        dialog.add(cancelButton);

        dialog.pack();
        dialog.setLocationRelativeTo(null);
        dialog.setVisible(true);
    }
}
